﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;

namespace NotifyServices
{
    public delegate ServiceResponse ServiceHelper(string ServiceName, string ServiceHost, string ServiceStatus);

    public class ServiceResponse
    {
        public string Host { get; set; }
        public string Service { get; set; }
        public string StatusDemanded { get; set; }
        public string CurrentStatus { get; set; }
        public bool UpdateSuccess { get; set; }
        public string Name { get; set; }
    }

    public class AsynchronousServiceManager
    {

        public ServiceHelper SetServiceStatus;

        public delegate void OnFinish(ServiceResponse e);

        public event OnFinish Finished;

        public AsynchronousServiceManager()
        {
            SetServiceStatus = new ServiceHelper(SetService); 
        }
        public void Update(string ServiceName, string ServiceHost, string ServiceStatus)
        {
            SetServiceStatus.BeginInvoke(ServiceName,ServiceHost,ServiceStatus, new AsyncCallback(CallbackMethod), null);
        }
        private ServiceResponse SetService(string name,string host,string state)
        {
            ServiceResponse response = new ServiceResponse() { 
                Host = host, 
                Service = name, 
                StatusDemanded = state,
                UpdateSuccess = false
            };

            ServiceController service = new ServiceController(name, host);

            if (state == "START")
            {
                if (service.Status != ServiceControllerStatus.Running)
                {
                    service.Start();
                    service.WaitForStatus(ServiceControllerStatus.Running);
                    response.UpdateSuccess = true;
                }
            }
            else if (state == "STOP")
            {
                if (service.Status != ServiceControllerStatus.Stopped && service.CanStop)
                {

                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped);
                    response.UpdateSuccess = true;
               }
            }
            response.CurrentStatus = service.Status.ToString();
            response.Name = service.DisplayName;
            return response;
        }


        private void CallbackMethod(IAsyncResult result)
        {
            ServiceResponse endresult = SetServiceStatus.EndInvoke(result);
           
            OnFinish handler = Finished;
            handler(endresult);
                
             
        }
    }
   
}
